package com.ruoyi.common.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.cert.X509Certificate;

/**
 * SSL工具类，用于处理SSL证书验证问题
 */
public class SslUtils {

    private static final Logger log = LoggerFactory.getLogger(SslUtils.class);

    private static boolean disabledSslVerification = false;

    /**
     * 禁用SSL证书验证
     * 警告：此方法会禁用所有SSL证书验证，仅应在开发或特定环境下使用
     */
    public static synchronized void disableSslVerification() {
        if (disabledSslVerification) {
            return;
        }

        try {
            // 创建信任所有证书的TrustManager
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[0];
                        }

                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                            // 不进行客户端证书校验
                        }

                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                            // 不进行服务器证书校验
                        }
                    }
            };

            // 创建SSL上下文并使用自定义的TrustManager
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());

            // 为HttpsURLConnection设置默认的SSLSocketFactory
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // 创建忽略主机名验证的HostnameVerifier
            HostnameVerifier allHostsValid = (hostname, session) -> true;
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

            // 关键部分：为Java HttpClient设置系统范围的信任管理器
            System.setProperty("jdk.internal.httpclient.disableHostnameVerification", "true");

            // 全局设置信任管理器（这是最重要的部分）
            System.setProperty("javax.net.ssl.trustStoreType", "WINDOWS-ROOT");
            System.setProperty("javax.net.ssl.trustStore", "NONE");
            System.setProperty("javax.net.ssl.trustStorePassword", "");

            // 创建临时信任库来信任所有证书
            createTrustAllKeyStore();

            disabledSslVerification = true;
            log.info("SSL证书验证已禁用，此设置仅适用于开发环境！");
        } catch (Exception e) {
            log.error("禁用SSL证书验证失败", e);
        }
    }

    /**
     * 创建信任所有证书的临时信任库
     */
    private static void createTrustAllKeyStore() {
        String tempDir = System.getProperty("java.io.tmpdir");
        String keyStorePath = tempDir + File.separator + "trustall.jks";

        try {
            // 如果已存在就删除
            Path path = Paths.get(keyStorePath);
            if (Files.exists(path)) {
                Files.delete(path);
            }

            // 创建空的KeyStore
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);

            // 保存KeyStore
            try (FileOutputStream fos = new FileOutputStream(keyStorePath)) {
                keyStore.store(fos, "changeit".toCharArray());
            }

            // 设置系统属性
            System.setProperty("javax.net.ssl.trustStore", keyStorePath);
            System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
            System.setProperty("javax.net.ssl.trustStoreType", KeyStore.getDefaultType());

            log.info("已创建信任所有证书的临时信任库：{}", keyStorePath);
        } catch (Exception e) {
            log.error("创建信任所有证书的临时信任库失败", e);
        }
    }
}